import 'package:app/components/index.dart';
import 'package:flutter/material.dart';

import '../../api/call-material/index.dart';
import '../../util/StringUtils.dart';
import 'package:qrscan/qrscan.dart' as scanner;

class CallMaterialDetail extends StatefulWidget{

  const CallMaterialDetail({super.key});

  @override
  State<CallMaterialDetail> createState() => CallMaterialDetailState();
}

class CallMaterialDetailState extends State<CallMaterialDetail>{

  //工序部门
  String _processDep = "";
  //工序班组
  String _processClass = "";
  //站点码
  String _code = "";
  //齐套状态
  String _status = "";
  // 拣配点ID
  String _pickId = "";
  // 托盘号
  String _container = "";

  final GlobalKey<FormState>? _formKey = GlobalKey<FormState>();

  //设置开始配送按钮是否可以点击
  bool isButtonEnabled = false;

  @override
  void initState() {
    super.initState();

    WidgetsBinding.instance.addPostFrameCallback((_){
      setParams(ModalRoute.of(context)!.settings.arguments);
      init();
    });

    // 在初始化时将焦点放在第一个文本框上
    WidgetsBinding.instance.addPostFrameCallback((_) {
      FocusScope.of(context).requestFocus(_firstFocusNode);
    });

  }

  final FocusNode _firstFocusNode = FocusNode();

  void scan() async{
    String? qrCode = await scanner.scan();
    setState(() => _code = qrCode.toString());
  }

  void setValue(String key, String value, bool bool){
    switch(key){
      case '_code' : _code = value;
      case 'isButtonEnabled' : isButtonEnabled = bool;
      break;
      default:
        throw Exception("key error");
    }
  }

  @override
  void dispose() {
    super.dispose();
    _firstFocusNode.dispose();
  }

  void hideKeyBorder(){
    FocusScopeNode currentFocus = FocusScope.of(context);
    if(!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null){
      FocusManager.instance.primaryFocus?.unfocus();
    }
  }

  /// 设置参数
  void setParams(params){
    setState(() {
      _processDep = params['processDep'];
      _processClass = params['processClass'];
      _code = params['code'];
      _status = params['status'];
      _pickId = params['pickId'].toString();
      _container = params['container'];
    });
  }

  //页面初始化 获取信息
  void init(){
    CallMaterialApi.of(context).detail(_pickId,_container).then((res){
      setState(() => _data = res.data['data']??[]);
    });
    if(_code.isNotEmpty){
      isButtonEnabled = true;
    }
  }

  /// 提交
  void submit(){
    Forms.validate(_formKey!).then((valid){
      if(valid){
        if(_status == "1"){
          createDelivery();
        }else{
          Confirm.of(context).show('物料不全，请确认是否配送？', ()=>{createDelivery()});
        }
      }
    });
  }

  /// 创建配送单
  void createDelivery(){
    CallMaterialApi.of(context).createDelivery({'endStation': _code, 'pickId': _pickId}).then((res){
      if(StringUtils.isNotNull(res) && StringUtils.isNotNull(res.data)){
        showSuccess();
      }
    });
  }

  void showSuccess(){
    Success.of(context).show('呼叫成功，请等待');
    Navigator.pop(context);
    Navigator.pushNamed(context, "/product-material-detail");
  }

  //设置table值
  List<dynamic> _data = [];

  Widget? show(index){
    if(_data[index]['type'] == '1'){
      return Horizontal(
          items: [
            HorizontalItem(
              label: '领料单号：',
              value: _data[index]['erpInvBillCode'],
            ),
            HorizontalItem(
              label: '状态：',
              value: _data[index]['status'] == '10' ? '拣配完成' :'',
              valueBackground: const Color.fromARGB(255, 110, 182, 239),
              fontColor: Colors.white,
            )
          ]
      );
    }
    return Container();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBars(context: context, title: '物料详细'),
      body: GestureDetector(
          onTap: hideKeyBorder,
          child: Container(
            color: const Color.fromARGB(255, 245, 245, 245),
            child: Column(
              children: [
                Group(
                  title: '班组信息',
                  context: context,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      Forms(
                        formKey: _formKey,
                        formItem: [
                          FormItem(
                            type: 'input',
                            labelText: '站  点  码:',
                            placeholder: '请扫描站点码',
                            focusNode: _firstFocusNode,
                            filedName: 'code',
                            icon: const Icon(Icons.qr_code_scanner_rounded),
                            value: _code,
                            iconOnTap: scan,
                            onChange: (value) => setValue(
                                '_code', value,
                                isButtonEnabled = true
                            ),
                            rules: const {'code': [{'required': true, 'message': '站点码不能为空'}]},
                          ),
                          FormItem(
                              type: 'input',
                              labelWidth: 90,
                              labelText: '工序部门:',
                              filedName: 'processOrg',
                              icon: const Icon(Icons.account_box),
                              value: _processDep,
                              enabled:false
                          ),
                          FormItem(
                              type: 'input',
                              labelWidth: 90,
                              labelText: '工序班组:',
                              filedName: 'processClass',
                              icon: const Icon(Icons.dashboard),
                              value: _processClass,
                              enabled:false
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
                Expanded(
                  child: ListContainer(
                      title: '物料信息',
                      length: _data.length,
                      children: (index){
                        return [
                          ListTitle(context: context,label: _data[index]['itemName'],),
                          Horizontal(
                              items: [
                                HorizontalItem(
                                  label: '物料编码：',
                                  value: _data[index]['itemCode']
                                ),
                                HorizontalItem(
                                  label: _data[index]['type'] == '1' ? "数量：": '缺料数量：',
                                  value: _data[index]['itemQty'].toString(),
                                  valueBackground: _data[index]['type'] == '1' ? Colors.lightBlueAccent : Colors.red,
                                  fontColor: Colors.white,
                                ),
                              ]
                          ),
                          show(index)!
                        ];
                      },
                  ),
                ),
                SizedBox(
                  width: MediaQuery.of(context).size.width,
                  child: Padding(
                    padding: const EdgeInsets.only(top: 10, left: 20, right: 20),
                    child: Button(
                      onPressed: isButtonEnabled ? submit : null,
                      backgroundColor: isButtonEnabled ? Color.fromARGB(255, 60, 98, 60) : Colors.grey,
                      label: '开始配送',
                      height: 60,
                      fontSize: 18,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
    );
  }
}